package com.snake.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import net.sf.json.JSONObject;



public class WxUtil {
	private static   Logger log = LoggerFactory.getLogger(WxUtil.class);
	public final static  String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	public final static  String access_token_url2 = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	public final static  String user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	//检验accessToken有效期
	public static boolean getAccessToken() {
		//Token token
		String accessToken = "";
		Long accessExpires =0L;
		boolean bo = true;
		/*if(token!=null&&!token.getAccessToken().equals("")){
			accessToken=token.getAccessToken();
			accessExpires=token.getExpiresIn();
			if(accessToken.equals("")||accessExpires==0){
				//jsonObject = getWXAccessToken(appid, appsecret);
				bo = false;
			}else{
				long currentTimeMillis = System.currentTimeMillis()+28800000;
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				Date date = simpleDateFormat.parse(accessExpires);
				long ts = date.getTime();
				accessExpires=accessExpires*1000;
				if (currentTimeMillis >=accessExpires) {
					bo = false;
				}else{
					bo = true;
					return bo;
				}
			}
		}else{
			bo = false;
		}*/
		return bo;
	}

	/**
	 * 获取access_token
	 * 
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
	 * @return
	 */
	public static Map<String, Object> getWXAccessToken(String appid, String appsecret,String code) {
		String requestUrl = access_token_url2.replace("APPID", appid).replace(
				"SECRET", appsecret).replace(
						"CODE", code);
		JSONObject jsonObject = HttpClientUtil.httpRequest(requestUrl, "GET", null);
		Map<String, Object> map = new HashMap<String, Object>();
		System.out.println("----------------getWXAccessToken:"+jsonObject.toString());
		// 如果请求成功
		if (jsonObject != null && jsonObject.containsKey("access_token")
				&& jsonObject.containsKey("expires_in")) {
			long currentTimeMillis = (System.currentTimeMillis()+28800000) / 1000;
			long expiresIn = jsonObject.getLong("expires_in");
			Long c = currentTimeMillis + expiresIn;
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date date = new Date(c * 1000);
			String accessExpires = simpleDateFormat.format(date);
			
			map.put("accessExpires", accessExpires);
			map.put("accessToken", jsonObject.getString("access_token"));
			map.put("refreshToken", jsonObject.getString("refresh_token"));
			map.put("scope", jsonObject.getString("scope"));
			
			map.put("openid", jsonObject.getString("openid"));
		} else {
			log.error("获取token失败 errcode:{} errmsg:{}",
					jsonObject.getInt("errcode"),
					jsonObject.getString("errmsg"));
			return map;
		}
		return map;
	}
	/**
	 * 验证微信用户AccessToken是否有效
	 * 
	 * @param accessToken
	 *            微信用户AccessToken
	 * @param openid
	 *            openid
	 * @return
	 */
	public static boolean getWXUserAccessToken(String accessToken, String openid) {
		String requestUrl = "https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID".replace("ACCESS_TOKEN", accessToken).replace(
				"OPENID", openid);
		JSONObject jsonObject = HttpClientUtil.httpRequest(requestUrl, "GET", null);
		Map<String, Object> map = new HashMap<String, Object>();
		boolean bo = true;
		// 如果请求成功
		if (jsonObject != null && jsonObject.containsKey("errcode")
				&& jsonObject.containsKey("errmsg")) {
			if(jsonObject.getInt("errcode")==0&&jsonObject.getString("errmsg").equals("ok")){
				return bo;
			}else{
				return false;
			}
		} else {
			return false;
			
		}
	}
	/**
	 * 网页授权获取微信用户信息
	 * 
	 * @param openid
	 *            用户openid
	 * @param accessToken
	 *            accessToken
	 * @return
	 */
	public static Map<String, Object> getWXUserInfos(String openid, String accessToken) {
		String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN".replace("ACCESS_TOKEN", accessToken).replace(
				"OPENID", openid);
		JSONObject jsonObject = HttpClientUtil.httpRequest(requestUrl, "GET", null);
		Map<String, Object> map = new HashMap<String, Object>();
		// 如果请求成功
		if (jsonObject != null && jsonObject.containsKey("nickname")) {
			System.out.println("-----------------nickname`1:"+jsonObject.getString("nickname"));
			map.put("nickName", jsonObject.getString("nickname"));
			map.put("sex", jsonObject.getInt("sex"));
			map.put("city", jsonObject.getString("city"));
			map.put("country", jsonObject.getString("country"));
			map.put("province", jsonObject.getString("province"));
			map.put("headimgurl", jsonObject.getString("headimgurl"));
			map.put("privilege", jsonObject.getString("privilege"));
		} 
		else {
			System.out.println("-----------------获取微信用户失败:"+jsonObject.toString());
			log.error("获取微信用户失败 errcode:{} errmsg:{}",
					jsonObject.getInt("errcode"),
					jsonObject.getString("errmsg"));
			return map;
		}
		return map;
	}
	/**
	 * 获取微信用户信息
	 * 
	 * @param openid
	 *            用户openid
	 * @param accessToken
	 *            accessToken
	 * @return
	 */
	public static Map<String, Object> getWXUserInfo(String openid, String accessToken) {
		String requestUrl = user_info_url.replace("ACCESS_TOKEN", accessToken).replace(
				"OPENID", openid);
		JSONObject jsonObject = HttpClientUtil.httpRequest(requestUrl, "GET", null);
		Map<String, Object> map = new HashMap<String, Object>();
		// 如果请求成功
		if (jsonObject != null && jsonObject.containsKey("subscribe")
				&& jsonObject.getString("subscribe").equals("1")) {
			System.out.println("-----------------subscribe`1:"+jsonObject.getString("subscribe"));
			map.put("nickName", jsonObject.getString("nickname"));
			map.put("sex", jsonObject.getInt("sex"));
			map.put("city", jsonObject.getString("city"));
			map.put("country", jsonObject.getString("country"));
			map.put("province", jsonObject.getString("province"));
			map.put("language", jsonObject.getString("language"));
			map.put("headimgurl", jsonObject.getString("headimgurl"));
			map.put("subscribeTime", jsonObject.getLong("subscribe_time"));
		} else if(jsonObject != null && jsonObject.containsKey("subscribe")
				&& jsonObject.getString("subscribe").equals("0")){
			System.out.println("-----------------subscribe0:"+jsonObject.getString("subscribe"));
			return map;
		}
		else {
			System.out.println("-----------------获取微信用户失败:");
			log.error("获取微信用户失败 errcode:{} errmsg:{}",
					jsonObject.getInt("errcode"),
					jsonObject.getString("errmsg"));
			return map;
		}
		return map;
	}
}
